document.addEventListener('DOMContentLoaded', function() {
    loadBooks();

    document.getElementById('book-form').addEventListener('submit', function(e) {
        e.preventDefault();
        addBook();
    });
});

function loadBooks() {
    fetch('/books')
        .then(response => response.json())
        .then(data => {
            const bookList = document.getElementById('book-list');
            bookList.innerHTML = '';
            data.forEach(book => {
                const row = `<tr>
                    <td>${book.id}</td>
                    <td>${book.title}</td>
                    <td>${book.author}</td>
                    <td>
                        <button onclick="editBook(${book.id})">编辑</button>
                        <button onclick="deleteBook(${book.id})">删除</button>
                    </td>
                </tr>`;
                bookList.innerHTML += row;
            });
        });
}

function addBook() {
    const title = document.getElementById('title').value;
    const author = document.getElementById('author').value;
    fetch('/books', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify({ title, author })
    })
    .then(response => response.json())
    .then(data => {
        loadBooks();
        document.getElementById('book-form').reset();
    });
}

function editBook(bookId) {
    const title = prompt('新的书名:', '');
    const author = prompt('新的作者:', '');
    if (title && author) {
        fetch(`/books/${bookId}`, {
            method: 'PUT',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({ title, author })
        })
        .then(response => response.json())
        .then(data => {
            loadBooks();
        });
    }
}

function deleteBook(bookId) {
    if (confirm('你确定要删除这本书吗?')) {
        fetch(`/books/${bookId}`, {
            method: 'DELETE'
        })
        .then(response => {
            if (response.ok) {
                loadBooks();
            }
        });
    }
}
